﻿namespace NTLib.Core.Pool
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;

    /// <summary>
    /// Base class for a pool item
    /// </summary>
    [DataContract]
    public abstract class PoolItem : IPoolItem
    {
        #region Fields

        private IPool _poolManager;

        private bool _itemDisposed;
        private bool _itemDestroyed;

        #endregion

        #region CTOR

        /// <summary>
        /// Initializes a new instance of the <see cref="PoolItem"/> class.
        /// </summary>
        protected PoolItem()
        {
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="PoolItem"/> class.
        /// </summary>
        ~PoolItem()
        {
            if (!this._itemDestroyed)
                Destroy();
        }

        #endregion

        #region Event

        /// <summary>
        /// Occurs when the item disposed.
        /// </summary>
        public event Action<object> ItemDisposed;

        #endregion

        #region Methods

        /// <summary>
        /// Destroys this instance.
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// This method must be called only by the pool managed when the instance is no more needed.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">This exception is raised if you called the destroy method more than once</exception>
        /// <remarks>
        /// This methods is used to free all the memory used by the object.
        /// </remarks>
        /// <permission cref="IPool">This Method must be called only by the pool manager.</permission>
        public void Destroy()
        {
            if (this._itemDestroyed)
                throw new ObjectDisposedException(this.GetType().Name);

            if (this._poolManager != null)
                this._poolManager.Destroy(this);

            try
            {
                ManagedDispose();
            }
            catch
            {

            }

            try
            {
                UnManagedDispose();
            }
            catch
            {

            }

            this._itemDestroyed = true;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// After the call of this method the object would be reinjected in the (<see cref="IPool" />) owner's pool to be reuse.
        /// </summary>
        /// <exception cref="System.AggregateException">Group all the exceptions raised during the dispose process.</exception>
        /// <remarks>If an exception occured the object is not recycle and not consider as disposed.</remarks>
        public void Dispose()
        {
            if (!this._itemDisposed)
            {

                List<Exception> exs = null;

                try
                {
                    ManagedDispose();
                }
                catch (Exception ex)
                {
                    if (exs == null)
                        exs = new List<Exception>();
                    exs.Add(ex);
                }

                try
                {
                    UnManagedDispose();
                }
                catch (Exception ex)
                {
                    if (exs == null)
                        exs = new List<Exception>();
                    exs.Add(ex);
                }

                if (exs != null)
                    throw new AggregateException(exs);

                if (this.ItemDisposed != null)
                    this.ItemDisposed(this);

                this._itemDisposed = true;

                if (this._poolManager != null)
                    this._poolManager.Recycle(this);
            }
        }

        /// <summary>
        /// Resets this instance.
        /// Everything MUST be initialized on this method.
        /// This method must be called only by the pool manager to initialize or reset the object.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">This exception is raised if you try to reset the reset a destroy's object.</exception>
        /// <remarks>
        /// In this method you must clear all the data of your object.
        /// </remarks>
        /// <permission cref="IPool">This Method must be called only by the pool manager.</permission>
        public void Reset(IPool poolManager)
        {
            if (this._itemDestroyed)
                throw new ObjectDisposedException(this.GetType().Name);

            this._poolManager = poolManager;

            OnReset();
            this._itemDisposed = false;
        }

        /// <summary>
        /// Called when the pool item is reset.
        /// Everything MUST be initialized on this method.
        /// </summary>
        protected abstract void OnReset();

        /// <summary>
        /// Dispose the managed objects.
        /// This method will be called everytime the object is disposed.
        /// </summary>
        protected virtual void ManagedDispose()
        {
        }

        /// <summary>
        /// Dispose the unmanaged objects.
        /// This method will be called everytime the object is disposed.
        /// </summary>
        protected virtual void UnManagedDispose()
        {
        }

        #endregion
    }
}
